//
// Created by renyi on 16/6/18.
//

#include "Sql_parse.h"

MYSQL* SQL_setup(){
    MYSQL *mysql;
    mysql= mysql_init(NULL);

    if (!mysql_real_connect(mysql, SQLHOST, USERNAME, PASSWORD,DBNAME, 0,  SQLRUN, 0)){
        printf("Error(%d) [%s] \"%s\"", mysql_errno(mysql),
               mysql_sqlstate(mysql),
               mysql_error(mysql));
        mysql_close(mysql);
        //exit(-1);
        return NULL;
    }

    return mysql;
}


int update(MYSQL *mysql, char *query){
    //sprintf(query, "UPDATE kj SET info='%s' WHERE  sn=%s", info, sn);
    //printf(query);
    if (mysql_real_query(mysql, query, strlen(query))){
        printf("Error(%d) [%s] \"%s\"", mysql_errno(mysql),
               mysql_sqlstate(mysql),
               mysql_error(mysql));
        //mysql_close(mysql);
    }

    //printf("affected_rows after UPDATE: %lu\n", (unsigned long) mysql_affected_rows(mysql));
    return (int) mysql_affected_rows(mysql);
}

int getInfo(MYSQL *mysql, char *sn, char* info){
    MYSQL_RES *result;
    char *query = (char*)malloc(sizeof(char)*1000);
    int has_sn, i_result = 0;

    sprintf(query, "SELECT * FROM kj where sn=%s", sn); //query= "SELECT * FROM kj where sn='ACPZ0FC206161'";
    //printf("%s\n", query);

    if (mysql_real_query(mysql, query, strlen(query))){
        printf("Error(%d) [%s] \"%s\"", mysql_errno(mysql),
               mysql_sqlstate(mysql),
               mysql_error(mysql));
        //mysql_close(mysql);
    }
    result= mysql_store_result(mysql);
    has_sn = (unsigned long) mysql_affected_rows(mysql);
    //printf("Affected_rows after SELECT and storing result set: %lu\n",has_sn);
    if (has_sn > 0){
        i_result = 1;
    }

    free(query);
    mysql_free_result(result);
    //mysql_close(mysql);
    return i_result;
}
/*
int check_sn(char *sn, char* info){
    MYSQL *mysql;
    MYSQL_RES *result;
    char *query = (char*)malloc(sizeof(char)*1000);
    int has_sn, i_result = 0;

    //mysql_debug("d:t:O");

    mysql= mysql_init(NULL);

    if (!mysql_real_connect(mysql, SQLHOST, USERNAME, PASSWORD,DBNAME, 0,  SQLRUN, 0))
        show_error(mysql);

    sprintf(query, "SELECT * FROM kj where sn=%s", sn); //query= "SELECT * FROM kj where sn='ACPZ0FC206161'";
    printf("%s\n", query);

    if (mysql_real_query(mysql, query, strlen(query)))
        show_error(mysql);
    result= mysql_store_result(mysql);

    has_sn = (unsigned long) mysql_affected_rows(mysql);
    //printf("Affected_rows after SELECT and storing result set: %lu\n",has_sn);

    if (has_sn > 0){
        i_result = 1;
    }

    free(query);
    mysql_free_result(result);
    mysql_close(mysql);

    return i_result;
}
*/